package com.xiangxiao.rpan.storage.dto;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.exception.FdfsUnsupportStorePathException;
import lombok.Getter;
import lombok.Setter;
import org.apache.commons.lang3.Validate;


/**
 * @auther xiangxiao
 * @email 573768011@qq.com
 * @data 2023/8/28 14:38
 */
@Getter
@Setter
public class StorePathDto extends StorePath {
  /**
   * 解析路径
   */
  private static final String SPLIT_GROUP_NAME_AND_FILENAME_SEPARATOR = "/";
  /**
   * group
   */
  private static final String SPLIT_GROUP_NAME = "group";
  private static final String SPLIT_RPANSTORE_NAME = "XX";

  private Long currByte;
  private Integer currChunk;
  private Integer totalChunks;
  private String path;
  private String group;

  public Integer getTotalChunks() {
    return totalChunks;
  }

  public void setTotalChunks(Integer totalChunks) {
    this.totalChunks = totalChunks;
  }

  public Integer getCurrChunk() {
    return currChunk;
  }

  public void setCurrChunk(Integer currChunk) {
    this.currChunk = currChunk;
  }

  public Long getCurrByte() {
    return currByte;
  }

  public void setCurrByte(Long currByte) {
    this.currByte = currByte;
  }

  public void setPath(String path) {
    this.path = path;
  }

  public String getPath() {
    return this.path;
  }

  public void setGroup(String group) {
    this.group = group;
  }

  public String getGroup() {
    return this.group;
  }

  public String getFullPath() {
    if (this.group != null) {
      return this.group.concat("/").concat(this.path);
    };
    return this.path;
  }

  /**
   * 从Url当中解析存储路径对象
   * @param filePath 有效的路径样式为(group/path) 或者
   *                 (http://ip/group/path),路径地址必须包含group
   * @return StorePath
   */
  public static StorePath praseFromUrl(String filePath) {
    Validate.notNull(filePath, "解析文件路径不能为空");
    // 获取group起始位置
    int groupStartPos = getGroupStartPos(filePath);
    String groupAndPath = filePath.substring(groupStartPos);

    int pos = groupAndPath.indexOf(SPLIT_GROUP_NAME_AND_FILENAME_SEPARATOR);
    if ((pos <= 0) || (pos == groupAndPath.length() - 1)) {
      throw new FdfsUnsupportStorePathException("解析文件路径错误,有效的路径样式为(group/path) 而当前解析路径为".concat(filePath));
    }

    String group = groupAndPath.substring(0, pos);
    String path = groupAndPath.substring(pos + 1);
    return new StorePath(group, path);
  }

  /**
   * 获得group起始位置
   *
   * @param filePath 文件路径
   * @return int
   */
  private static int getGroupStartPos(String filePath) {
    int pos = filePath.indexOf(SPLIT_GROUP_NAME);
    if ((pos == -1)) {
      pos = filePath.indexOf(SPLIT_RPANSTORE_NAME);
      if ((pos == -1)) {
        throw new FdfsUnsupportStorePathException("解析文件路径错误,被解析路径url没有group或XX,当前解析路径为".concat(filePath));
      }
    }
    return pos;
  }
}
